<template>
  <MainLayout title="预拌混凝土施工记录">
    <view class="page">

      <!-- 基本信息 -->
      <view class="sec-hd">基本信息</view>
      <view class="form">
        <view class="row">
          <text class="lbl">工程名称</text>
          <input class="ipt" v-model="form.projectName" placeholder="请输入" />
        </view>
        <view class="row">
          <text class="lbl">天气</text>
          <input class="ipt" v-model="form.weather" placeholder="如 阴/晴" />
        </view>
        <view class="row">
          <text class="lbl">温度</text>
          <input class="ipt" v-model="form.temperature" placeholder="如 8-13" />
        </view>
        <view class="row">
          <text class="lbl">页码</text>
          <input class="ipt" v-model.number="form.pageNo" type="number" placeholder="1" />
        </view>
        <view class="row">
          <text class="lbl">砼浇筑部位</text>
          <input class="ipt" v-model="form.supplyUnit" placeholder="构件、标高及名称" />
        </view>
        <view class="row">
          <text class="lbl">砼设计强度</text>
          <input class="ipt" v-model="form.designStrength" placeholder="如 45 (MPa)" />
        </view>
        <view class="row">
          <text class="lbl">拌和站名称</text>
          <input class="ipt" v-model="form.mixPlant" placeholder="请输入" />
        </view>
        <view class="row">
          <text class="lbl">联系电话</text>
          <input class="ipt" v-model="form.contactPhone" placeholder="请输入" />
        </view>

        <!-- 浇筑时间（原生 picker：date+time 组合） -->
        <view class="row">
          <text class="lbl">浇筑开始</text>
          <view class="dt">
            <picker mode="date" :value="startDate" @change="e=>startDate=e.detail.value">
              <view class="picker">{{ startDate || '选择日期' }}</view>
            </picker>
            <picker mode="time" :value="startTime" @change="e=>startTime=e.detail.value">
              <view class="picker">{{ startTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>
        <view class="row">
          <text class="lbl">浇筑结束</text>
          <view class="dt">
            <picker mode="date" :value="endDate" @change="e=>endDate=e.detail.value">
              <view class="picker">{{ endDate || '选择日期' }}</view>
            </picker>
            <picker mode="time" :value="endTime" @change="e=>endTime=e.detail.value">
              <view class="picker">{{ endTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>

        <view class="row">
          <text class="lbl">坍落度</text>
          <input class="ipt" v-model="form.slump" placeholder="如 234 mm" />
        </view>
        <view class="row">
          <text class="lbl">连续浇筑工时</text>
          <input class="ipt" v-model="form.continuousTime" placeholder="请输入" />
        </view>
        <view class="row">
          <text class="lbl">初凝时间</text>
          <input class="ipt" v-model="form.initialSetting" placeholder="如 4小时" />
        </view>
        <view class="row">
          <text class="lbl">试块推荐强度</text>
          <input class="ipt" v-model="form.cubeStrength" placeholder="如 45 MPa" />
        </view>
      </view>

      <!-- 车号 -->
      <view class="sec-hd">搅拌运输车编号</view>
      <view class="list">
        <view class="list-row" v-for="(no,i) in form.truckNos" :key="'t'+i">
          <input class="ipt flex1" v-model="form.truckNos[i]" placeholder="车号" />
          <button size="mini" @click="form.truckNos.splice(i,1)">删除</button>
        </view>
        <button class="btn-add" @click="form.truckNos.push('')">+ 添加车号</button>
      </view>

      <!-- 检查事项 -->
      <view class="sec-hd">施工事项检查</view>
      <view class="list">
        <view class="list-row" v-for="(it,i) in form.checklist" :key="'c'+i">
          <input class="ipt no" v-model="it.no" placeholder="序号" />
          <input class="ipt flex1" v-model="it.title" placeholder="检查项" />
          <input class="ipt flex1" v-model="it.result" placeholder="结论（齐全/符合要求...）" />
          <button size="mini" @click="form.checklist.splice(i,1)">删</button>
        </view>
        <button class="btn-add" @click="addChecklist()">+ 添加检查项</button>
      </view>

      <!-- 取样/试块 -->
      <view class="sec-hd">取样与试块</view>
      <view class="form">
        <view class="row">
          <text class="lbl">取样总次数</text>
          <input class="ipt" v-model.number="form.samplingTimes" type="number" placeholder="0" />
        </view>
        <view class="row">
          <text class="lbl">抗渗试块</text>
          <input class="ipt" v-model="form.rebarValue" placeholder="组数/等级" />
        </view>
        <view class="row">
          <text class="lbl">同条件(当前)</text>
          <input class="ipt" v-model.number="form.cubeGroupsCurr" type="number" placeholder="0" />
        </view>
        <view class="row">
          <text class="lbl">其中中等强度</text>
          <input class="ipt" v-model.number="form.cubeGroupsMid" type="number" placeholder="0" />
        </view>
        <view class="row">
          <text class="lbl">拆模同条件</text>
          <input class="ipt" v-model.number="form.cubeGroupsSpl" type="number" placeholder="0" />
        </view>
      </view>

      <view class="list">
        <view class="sub-hd">其检验值（mm）分别为</view>
        <view class="list-row" v-for="(v,i) in form.samplingValues" :key="'sv'+i">
          <input class="ipt flex1" v-model.number="form.samplingValues[i]" type="number" placeholder="检验值" />
          <button size="mini" @click="form.samplingValues.splice(i,1)">删</button>
        </view>
        <button class="btn-add" @click="form.samplingValues.push(null)">+ 添加检验值</button>
      </view>

      <!-- 其他 -->
      <view class="sec-hd">其他</view>
      <view class="form">
        <view class="row">
          <text class="lbl">检查落实说明</text>
          <textarea class="ta" v-model="form.inspectorOpinion" placeholder="请输入"></textarea>
        </view>
        <view class="row">
          <text class="lbl">记录真实可靠</text>
          <switch :checked="form.isTrue" @change="e=>form.isTrue=e.detail.value" />
        </view>
        <view class="row">
          <text class="lbl">记录人</text>
          <input class="ipt" v-model="form.recorder" placeholder="请输入" />
        </view>
      </view>

      <!-- 操作 -->
      <view class="ops">
        <button type="primary" class="op" @click="onSave">保存</button>
        <button class="op" :disabled="!form.id" @click="onExport">导出 PDF</button>
      </view>
    </view>
  </MainLayout>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import MainLayout from '@/layouts/MainLayout.vue'
import { rmc } from '@/services/api'
import {downloadBlob} from "../../services/api";

type ChecklistItem = { no: number | string; title: string; result: string }

const form = reactive<any>({
  id: null,
  projectId: 0,
  projectName: '',
  weather: '',
  temperature: '',
  pageNo: 1,
  supplyUnit: '',
  designStrength: '',
  mixPlant: '',
  contactPhone: '',
  // 保存时拼接
  pouringDateStart: '',
  pouringDateEnd: '',
  slump: '',
  continuousTime: '',
  initialSetting: '',
  cubeStrength: '',
  truckNos: [''],
  checklist: [] as ChecklistItem[],
  samplingTimes: 0,
  samplingValues: [] as number[],
  cubeGroupsCurr: 0,
  cubeGroupsMid: 0,
  cubeGroupsSpl: 0,
  rebarValue: '',
  inspectorOpinion: '',
  recorder: '',
  isTrue: true
})

// 原生 picker 的日期/时间（单独维护，再合并）
const startDate = ref<string>(''); const startTime = ref<string>('')
const endDate   = ref<string>(''); const endTime   = ref<string>('')

onLoad(async (q:any) => {
  form.projectId = Number(q?.project_id || q?.projectId || 0)
  if (q?.id) {
    const res = await rmc.getById(Number(q.id))
    const data = res?.data || res
    Object.assign(form, data)
    // 若后端返回了完整时间，拆成 date+time 以供 picker 显示
    if (form.pouringDateStart) [startDate.value, startTime.value] = splitDT(form.pouringDateStart)
    if (form.pouringDateEnd)   [endDate.value,   endTime.value]   = splitDT(form.pouringDateEnd)
  }
})

function splitDT(dt: string): [string, string] {
  // 支持 'YYYY-MM-DD HH:mm:ss' 或 ISO
  const t = dt.replace('T', ' ')
  const [d, time] = t.split(' ')
  return [d, (time || '').slice(0,5)]
}

function addChecklist(){
  form.checklist.push({ no: (form.checklist.length+1), title:'', result:'' })
}

function toISO(date:string, time:string){
  if(!date || !time) return ''
  // 统一转 ISO，便于后端 LocalDateTime 接收
  const s = `${date} ${time}:00`
  const d = new Date(s.replace(/-/g,'/'))
  return isNaN(+d) ? s : d.toISOString()
}

async function onSave(){
  form.pouringDateStart = toISO(startDate.value, startTime.value)
  form.pouringDateEnd   = toISO(endDate.value,   endTime.value)
  const ret = await rmc.save({ ...form })
  if (ret?.id) form.id = ret.id
  uni.showToast({ title:'已保存', icon:'success' })
}

const API_BASE =
    (import.meta as any).env?.VITE_API_BASE?.trim()
        ? (import.meta as any).env.VITE_API_BASE.trim().replace(/\/+$/, '')
        : '/api' // 默认值

// function onExport(){
//   if(!form.id){ uni.showToast({ title:'请先保存', icon:'none' }); return }
//   // const url = `${API_BASE}/rmc/${form.id}/export?projectName=${encodeURIComponent(form.projectName||'')}`
//   // console.log('export url =', url)
//   const bin = await rmc.exportPdf(form.id, form.projectName)
//   if (typeof window !== 'undefined' && bin instanceof Blob) {
//     downloadBlob(bin, `预拌混凝土施工记录_${form.id}.pdf`)
//   }
//   // H5 直接新窗口；非 H5 用 downloadFile
//   // @ts-ignore
//   if (typeof window !== 'undefined') window.open(url, '_blank')
//   else uni.downloadFile({ url })
// }

async function onExport() {
  if (!form.id) {
    uni.showToast({ title: '请先保存', icon: 'none' })
    return
  }
  try {
    const bin = await rmc.exportPdf(form.id, form.projectName)

    // H5：下载
    // @ts-ignore
    if (typeof window !== 'undefined' && bin instanceof Blob) {
      downloadBlob(bin, `预拌混凝土施工记录_${form.id}.pdf`)
      return
    }

    // 非 H5：bin 是 ArrayBuffer，可按需保存（可先简单提示）
    uni.showToast({ title: '导出成功（非H5请按端内保存处理）', icon: 'success' })
  } catch (e: any) {
    uni.showToast({ title: e?.message || '导出失败', icon: 'none' })
  }
}
</script>

<style scoped>
.page { padding: 12px; }
.sec-hd { font-weight: 600; margin: 14px 0 8px; font-size: 15px; }
.sub-hd { margin: 8px 0; color:#666; }

.form .row { display:flex; align-items:center; gap:10px; margin:8px 0; }
.lbl { width: 100px; color:#444; }
.ipt { flex:1; min-height: 36px; padding: 6px 8px; border: 1px solid #e6e6e6; border-radius: 6px; background:#fff; }
.ta  { width: 100%; min-height: 90px; padding: 6px 8px; border: 1px solid #e6e6e6; border-radius: 6px; background:#fff; }

.dt { display:flex; gap:8px; flex:1; }
.picker { min-width:120px; padding: 6px 8px; border:1px solid #e6e6e6; border-radius:6px; background:#fff; color:#333; }

.list { margin-top: 6px; }
.list-row { display:flex; align-items:center; gap:8px; margin:6px 0; }
.flex1 { flex:1; }
.no { width: 60px; text-align:center; }

.btn-add { margin: 6px 0 12px; padding: 6px 10px; border:1px dashed #bdbdbd; background:#fff; border-radius:6px; color:#333; }

.ops { display:flex; gap:12px; margin: 18px 0 28px; }
.op { padding: 10px 14px; border-radius: 6px; }
</style>
